package com.net.xpay.openapi.controller.openapi;


import com.google.common.base.Strings;
import com.net.xpay.openapi.protocol.Signer;
import com.net.common.util.SerializationUtil;
import com.net.xpay.common.annotation.ApiMonitoring;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/apiv1/openapi/test")
@Api(tags = "第三方开放调用/测试", description = "第三方开放调用 充值服务费")
public class OpenApiTestController {

    private static final String OPENAPI_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1sx/JzdM5T06/yeYlXj12vp4XtM/ByRy3RuxNYP4DFiw0VRZ1J2s0ENp7IrTJ+nsEh1m3of+BeCOCxON/Q3KnksAjAjCWexp0wVA+mvY8dGOMqH++Q/++U0DQw2yxxAzZkf7sDwtZcJSwSUFrRDY9SBQysfJM3T1CiMhDT87+eiBZsa68YL56p7bLDHuoAvfh/aDgSPh50umKU23rZQZ4Okqx57WBiOsjXeK7IkfMtsNnGQ5LPWlPlsOMy7/n7wKCqOCbhwZ7v2cuZZTFEuMF6qaj9ytAT/vD+iXvkW1MZySNHOzxKpC6HN4TmoEyX4Y8qcdNSvT/LGinKNLX7BjdQIDAQAB";

    @ApiMonitoring("测试/测试推送")
    @ApiOperation(value = "测试推送")
    @PostMapping("/notify")
    public String testNotify(HttpServletRequest request) {
        log.info("testNotify request={}", SerializationUtil.obj2String(request.getParameterMap()));

        Map<String, String> map = new HashMap<>();

        request.getParameterMap().forEach((k, v) -> {
            if (!Strings.isNullOrEmpty(v[0])) {
                map.put(k, v[0]);
            }
        });


        log.info("testNotify params={}", SerializationUtil.obj2String(map));

        boolean sign = Signer.verifyParams(map, OPENAPI_PUBLIC_KEY);
        if (sign) {
            log.info("签名验证通过");
            return "success";
        } else {
            log.info("签名验证失败");
            return "error";
        }

    }

}
